<?php

function siteaccess_demo_init() {
  extend_view('js/initialise_elgg','siteaccess_demo/js');
  extend_view('css', 'siteaccess_demo/css');
  register_elgg_event_handler('create', 'user', 'siteaccess_demo_create_user');
  
  extend_view('siteaccess/register', 'siteaccess_demo/register');
//  extend_view('siteaccess/login', 'siteaccess_demo/login');
  register_plugin_hook('action', 'register', 'siteaccess_demo_register_hook');
  register_plugin_hook('action', 'login', 'siteaccess_demo_login_hook');
}

function siteaccess_demo_login_hook($hook, $entity_type, $returnvalue, $params) {
/*
  $checkbox = get_input('login_checkbox');
  
  if (!$checkbox) {
    register_error(elgg_echo('siteaccess:demo:login:error'));
    return false;
  }
*/

}

function siteaccess_demo_dateDiff($dformat, $endDate, $beginDate) { //frá http://www.developertutorials.com/tutorials/php/calculating-difference-between-dates-php-051018/page1.html
	$date_parts1=explode($dformat, $beginDate);
	$date_parts2=explode($dformat, $endDate);
	$start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
	$end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
	return $end_date - $start_date;
}

function siteaccess_demo_register_hook($hook, $entity_type, $returnvalue, $params) {
//  $checkbox = get_input('register_checkbox');
  $dob = get_input('datepicker');
  
  if ( !$dob ) {
    register_error(elgg_echo('siteaccess:demo:register:error'));
    
    if (function_exists('siteaccess_register_fail')) {
      siteaccess_register_fail();
    }
    return false;
  }

  $ageInYears = round(siteaccess_demo_dateDiff("-", date("Y-m-d", time()), $dob)/365, 0);
  if ( $ageInYears < 18 ) {
    register_error(elgg_echo('siteaccess:demo:register:underage'));
    
    if (function_exists('siteaccess_register_fail')) {
      siteaccess_register_fail();
    }
    return false;
  }
}

function siteaccess_demo_create_user($event, $object_type, $object) {
  if (($object) && ($object instanceof ElggUser)) {
    $dob = get_input('datepicker');
    create_metadata($object->guid, 'dob', $dob,'', 0, ACCESS_PUBLIC);
  }
}

register_elgg_event_handler('init','system','siteaccess_demo_init');
?>
